import wx from './jweixin-module/lib/index.js'

function H5weixin(action, params) {
  const uniIdToken = uni.getStorageSync('uni_id_token')
  return new Promise((resolve, reject) => {
    uniCloud.callFunction({
      name: 'H5weixin',
      data: {
        action,
        uniIdToken,
        params
      },
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 判断是否是微信内置浏览器
const isWechat = function () {
  return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === 'micromessenger'
}

// 在IOS上，无论路由切换到哪个页面，实际真正有效的的签名URL是【第一次进入应用时的URL】
const isIos = function () {
  return navigator.userAgent.includes('iPhone') || navigator.userAgent.includes('Mac OS')
}

// 获取链接参数
const getParam = function (name) {
  const a = (new RegExp(`[?|&]${name}=` + `([^&;]+?)(&|#|;|$)`).exec(location.href) || ['', ''])[1].replace(/\+/g, '%20')
  return a
}

// h5微信登录第一步
const wxH5LoginSep1 = async function () {
  const openid = uni.getStorageSync('openid')
  if (openid) {
    console.log('已授权过', openid)
    return { openid }
  }
  else {
    const key = 'appId'
    const config = await H5weixin('config', { key })
    const appid = config.result
    const redirect_uri = encodeURIComponent(location.href)// url要编码
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=mystate#wechat_redirect`
  }
}
// 微信登录第二步和第三步
const wxH5LoginSep2 = async function (showloading) {
  // 如果已经有了openid，直接返回
  const openid = uni.getStorageSync('openid')
  if (openid) return { openid }
  // 通过code换取网页授权access_token
  const state = getParam('state')
  const code = getParam('code')
  if (state === 'mystate') {
    if (showloading) {
      uni.showLoading({
        title: '登录中'
      })
    }
  }
  else {
    return
  }
  /* 获取openid和用户信息并登录注册 */
  // let res = await H5weixin('weixinlogin', {code})
  /* 只获取openid和用户信息，自己自定义登陆注册方法 */
  const res = await H5weixin('getOpenid', { code })
  // 登录失败代码
  if (!res.result.success) {
    uni.showToast({
      icon: 'error',
      title: res.result.message
    })
  }
  else {
    // 登录成功代码
    uni.setStorageSync('openid', res.result.openid)
    if (showloading) {
      uni.hideLoading()
    }
    return res.result
  }
}

/* 获取用户订阅信息 */
async function subscribe(openid) {
  const res = await H5weixin('subscribe', { openid })
  return res.result
}

/* 获取配置 */
async function getsdk(jsApiList) {
  const url = window.location.href.split('#')[0]
  const res = await H5weixin('getsdk', { url })
  const config = {
    debug: false,
    appId: res.result.appId, // 必填，公众号的唯一标识
    timestamp: res.result.timestamp, // 必填，生成签名的时间戳
    nonceStr: res.result.noncestr, // 必填，生成签名的随机串
    signature: res.result.signature, // 必填，签名，见附录1
    jsApiList

  }
  return config
}
/* 分享设置 */
async function shareSet(title, desc, imgUrl, link) {
  const jsApiList = [
    'updateTimelineShareData',
    'updateAppMessageShareData'
  ]
  const config = await getsdk(jsApiList)

  wx.config(config)
  wx.error((res) => {
    console.log('JS-SDK配置出问题了', res)
  })
  wx.ready(() => {
    // 自定义分享的内容，开发者可以自主修改这部分内容
    const shareData1 = {
      title,
      link,
      imgUrl,
      success(res) {
        console.log('分享设置成功', res)
      }
    }
    const shareData2 = {
      ...shareData1,
      desc
    }
    wx.updateAppMessageShareData(shareData2)
    wx.updateTimelineShareData(shareData1)
  })
}

const notice = async function (allopenid, url, noticedata, template_id) {
  const res = await H5weixin('notice', { allopenid, url, noticedata, template_id })
  return res
}

const scanQRCode = async function () {
  const jsApiList = ['scanQRCode']
  const config = await getsdk(jsApiList)
  wx.config(config)
  wx.error((res) => {
    console.log('JS-SDK配置出问题了', res)
  })
  wx.scanQRCode({
    needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
    scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
    success(res) {
      const result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
      return result
    }
  })
}

const hideMenuItems = async function (menuList) {
  const jsApiList = ['hideMenuItems']
  const config = await getsdk(jsApiList)
  wx.config(config)
  wx.error((res) => {
    console.log('JS-SDK配置出问题了', res)
  })
  wx.hideMenuItems({
    menuList
  })
}

export default {
  getsdk,
  shareSet,
  notice,
  wxH5LoginSep1,
  wxH5LoginSep2,
  getParam,
  isWechat,
  scanQRCode,
  hideMenuItems,
  subscribe
}
